import axios from 'axios'
import { message } from 'antd'
import { useAuthStore } from '../store/authStore'

// 开发环境使用相对路径，通过 Vite 代理转发
// 生产环境使用环境变量或默认值
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || (import.meta.env.DEV ? '' : 'http://localhost:3001')

const request = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = useAuthStore.getState().token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data
  },
  async (error) => {
    if (error.response) {
      const { status, data } = error.response

      if (status === 401) {
        // Token 过期，尝试刷新
        const { refreshToken, updateToken, logout } = useAuthStore.getState()
        if (refreshToken) {
          try {
            const refreshUrl = API_BASE_URL ? `${API_BASE_URL}/auth/refresh` : '/auth/refresh'
            const response = await axios.post(refreshUrl, {
              refresh_token: refreshToken,
            })
            updateToken(response.data.access_token)
            // 重试原请求
            return request(error.config)
          } catch (refreshError) {
            logout()
            window.location.href = '/login'
            return Promise.reject(refreshError)
          }
        } else {
          logout()
          window.location.href = '/login'
        }
      }

      message.error(data?.error || '请求失败')
      return Promise.reject(error)
    }

    message.error('网络错误，请检查网络连接')
    return Promise.reject(error)
  }
)

export default request


